import 'package:dailoz/constants.dart';
import 'package:dailoz/dio/http_util.dart';
import 'package:dailoz/entity/task_entity.dart';
import 'package:dailoz/response_json_entity.dart';
import 'package:dailoz/size_config.dart';
import 'package:dailoz/view_model/task_type.dart';
import 'package:dailoz/views/task_type_detail.dart';
import 'package:dailoz/widgets/label_type.dart';
import 'package:dailoz/widgets/task_label.dart';
import 'package:dailoz/widgets/task_widget.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dailoz/generated/l10n.dart' as lang;

class HomePageService {
  static Future<String?> getName() async {
    String? username;
    final prefs = await SharedPreferences.getInstance();
    username = prefs.getString("user-name");
    return username;
  }

  static Future<List> getTodayTask() async {
    List todayTaskList = [];
    try {
      final prefs = await SharedPreferences.getInstance();
      var response = await HttpUtil().get('/task/todayTask',
          data: {"id": prefs.getString("user-id"), "options": DateTime.now()});
      if (response != null) {
        ResponseJsonEntity responseJsonEntity =
            ResponseJsonEntity.fromJson(response);
        if (responseJsonEntity.data != null) {
          todayTaskList = responseJsonEntity.data;
        }
      }
      return todayTaskList;
    } catch (e) {
      print(e);
      return todayTaskList;
    }
  }

  static Future<List> getStatusTask() async {
    List statusTaskList = [];
    final prefs = await SharedPreferences.getInstance();
    try {
      var response = await HttpUtil()
          .get('/task/statusTask', data: {"id": prefs.getString("user-id")});
      if (response['data'] != null) {
        statusTaskList = response['data'];
      }
      return statusTaskList;
    } catch (e) {
      print(e);
      return statusTaskList;
    }
  }

  static Widget generateTask(List todayTaskList, BuildContext context) {
    List<Widget> task = [];
    List<Widget> taskChild = [];
    if (todayTaskList.isNotEmpty) {
      for (var todayTask in todayTaskList) {
        TaskEntity taskEntity = TaskEntity.fromJson(todayTask);
        if (taskEntity.tag != "" && taskEntity.tag != null) {
          List<String> tagList = taskEntity.tag.split(",");
          for (String type in tagList) {
            taskChild.add(
              TaskLabel(
                status: taskEntity.status,
                labelName: type,
              ),
            );
            taskChild.add(
              const SizedBox(
                width: 6.0,
              ),
            );
          }
        }
        String startTime =
            formatDate(DateTime.parse(taskEntity.startTime), [HH, ':', nn]);
        String endTime =
            formatDate(DateTime.parse(taskEntity.endTime), [HH, ':', nn]);
        task.add(
          TaskWidget(
            task: taskEntity,
            parentFunction: () => null,
            taskId: taskEntity.id!,
            padding: const EdgeInsets.symmetric(horizontal: 20.0),
            margin: EdgeInsets.only(
              top: SizeConfig.getProportionateScreenHeight(10.0),
            ),
            height: SizeConfig.getProportionateScreenHeight(114.0),
            width: SizeConfig.getProportionateScreenWidth(322.0),
            taskName: taskEntity.taskContent,
            taskTime: "$startTime - $endTime",
            labelGroupPadding: EdgeInsets.only(
              bottom: SizeConfig.getProportionateScreenHeight(15),
            ),
            taskLabel: taskChild,
          ),
        );
        taskChild = [];
      }
    } else {
      return Padding(
        padding:
            EdgeInsets.only(top: SizeConfig.getProportionateScreenHeight(28.0)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              lang.S.of(context).NoSchedule,
              style: const TextStyle(
                color: Color(0xff575757),
              ),
            ),
            SizedBox(
              height: SizeConfig.getProportionateScreenHeight(10.0),
            ),
            Text(
              lang.S.of(context).createNewTask,
              style: const TextStyle(
                color: Color(0xff575757),
              ),
            ),
          ],
        ),
      );
    }
    return Column(
      children: task,
    );
  }

  static List<Widget> generateStatusTask(
      List statusTaskList, BuildContext context) {
    List<Widget> list = [];
    int completedNum = 0;
    int cancelNum = 0;
    int pendingNum = 0;
    int onGoingNum = 0;
    for (var list in statusTaskList) {
      switch (list['status']) {
        case 1:
          completedNum = int.parse(list['num']);
          break;
        case 2:
          cancelNum = int.parse(list['num']);
          break;
        case 3:
          pendingNum = int.parse(list['num']);
          break;
        case 4:
          onGoingNum = int.parse(list['num']);
          break;
        default:
      }
    }
    list.add(Column(
      children: <Widget>[
        LabelType(
          onTap: () async {
            final prefs = await SharedPreferences.getInstance();
            prefs.setInt("taskStatus", 1);
            // ignore: use_build_context_synchronously
            Navigator.pushNamed(
              context,
              TaskTypeDetail.id,
              arguments: TaskType(
                // ignore: use_build_context_synchronously
                lang.S.of(context).completed,
                completedTaskBoxColor,
                1,
              ),
            );
          },
          boxWidth: 155.0,
          boxHeight: 155.0,
          crossAxisAlignment: CrossAxisAlignment.start,
          childPadding: EdgeInsets.only(
            left: SizeConfig.getProportionateScreenWidth(15.0),
          ),
          labelName: lang.S.of(context).completed,
          taskNum: completedNum,
          labelColor: const Color(0xff7dc8e7),
          taskNumColor: homeColor,
          taskNumSize: 14.0,
          labelNameColor: homeColor,
          labelNameSize: 16.0,
          // child: Image(
          //   image: const AssetImage("assets/images/computer.png"),
          //   height: SizeConfig.getProportionateScreenHeight(69.0),
          //   width: SizeConfig.getProportionateScreenWidth(92.0),
          // ),
          child: SvgPicture.asset(
            "assets/images/computer.svg",
            height: SizeConfig.getProportionateScreenHeight(69.0),
            width: SizeConfig.getProportionateScreenWidth(92.0),
          ),
        ),
        SizedBox(
          height: SizeConfig.getProportionateScreenHeight(16.0),
        ),
        LabelType(
          onTap: () async {
            final prefs = await SharedPreferences.getInstance();
            prefs.setInt("taskStatus", 2);
            // ignore: use_build_context_synchronously
            Navigator.pushNamed(
              context,
              TaskTypeDetail.id,
              arguments: TaskType(
                // ignore: use_build_context_synchronously
                lang.S.of(context).cancel,
                cancelTaskBoxColor,
                2,
              ),
            );
          },
          boxHeight: 116.0,
          boxWidth: 153.0,
          labelName: lang.S.of(context).cancel,
          taskNum: cancelNum,
          labelColor: cancelTaskColor,
          labelNameSize: 16.0,
          labelNameColor: Colors.white,
          taskNumSize: 14.0,
          taskNumColor: Colors.white,
          crossAxisAlignment: CrossAxisAlignment.start,
          childPadding: EdgeInsets.only(
            left: SizeConfig.getProportionateScreenWidth(15.0),
          ),
          child: Icon(
            Icons.cancel_outlined,
            color: Colors.white,
            size: SizeConfig.getProportionateFontSize(28),
          ),
        ),
      ],
    ));
    list.add(SizedBox(
      width: SizeConfig.getProportionateScreenWidth(16.0),
    ));
    list.add(Column(
      children: <Widget>[
        LabelType(
          onTap: () async {
            final prefs = await SharedPreferences.getInstance();
            prefs.setInt("taskStatus", 3);
            // ignore: use_build_context_synchronously
            Navigator.pushNamed(
              context,
              TaskTypeDetail.id,
              arguments: TaskType(
                // ignore: use_build_context_synchronously
                lang.S.of(context).pending,
                pendingTaskBoxColor,
                3,
              ),
            );
          },
          boxWidth: 155.0,
          boxHeight: 116.0,
          labelName: lang.S.of(context).pending,
          taskNum: pendingNum,
          labelColor: pendingTaskColor,
          labelNameColor: Colors.white,
          labelNameSize: 16.0,
          taskNumColor: Colors.white,
          taskNumSize: 14.0,
          crossAxisAlignment: CrossAxisAlignment.start,
          childPadding: EdgeInsets.only(
            left: SizeConfig.getProportionateScreenWidth(15.0),
          ),
          child: Icon(
            Icons.access_time_outlined,
            color: Colors.white,
            size: SizeConfig.getProportionateFontSize(28.0),
          ),
        ),
        SizedBox(
          height: SizeConfig.getProportionateScreenHeight(16.0),
        ),
        LabelType(
          onTap: () async {
            final prefs = await SharedPreferences.getInstance();
            prefs.setInt("taskStatus", 4);
            // ignore: use_build_context_synchronously
            Navigator.pushNamed(
              context,
              TaskTypeDetail.id,
              arguments: TaskType(
                // ignore: use_build_context_synchronously
                lang.S.of(context).ongoing,
                onGoingTaskBoxColor,
                4,
              ),
            );
          },
          boxHeight: 152.0,
          boxWidth: 155.0,
          labelName: lang.S.of(context).ongoing,
          taskNum: onGoingNum,
          labelColor: onGoingTaskColor,
          crossAxisAlignment: CrossAxisAlignment.start,
          childPadding: EdgeInsets.only(
            left: SizeConfig.getProportionateScreenWidth(15.0),
          ),
          labelNameColor: homeColor,
          labelNameSize: 16.0,
          taskNumSize: 14.0,
          taskNumColor: homeColor,
          // child: Image(
          //   image: const AssetImage("assets/images/Folder.png"),
          //   width: SizeConfig.getProportionateScreenWidth(92.0),
          //   height: SizeConfig.getProportionateScreenHeight(69.0),
          // ),
          child: SvgPicture.asset(
            "assets/images/send.svg",
            height: SizeConfig.getProportionateScreenHeight(69.0),
            width: SizeConfig.getProportionateScreenWidth(92.0),
          ),
        ),
      ],
    ));
    return list;
  }
}
